import { Table } from "@/hooks/interface/table";

export const useTable = (api: (params: any) => Promise<any>, initParam: object = {}, isPageable: boolean = true) => {
  const state = reactive<Table.StateProps>({
    // 表格数据
    tableData: [],
    loading: false,
    loadStatus: "more",
    // 分页数据
    pageable: {
      // 当前页数
      pageNum: 1,
      // 每页显示条数
      pageSize: 10,
      // 总条数
      total: 0
    },
    totalParam: {},
    // 初始化默认的查询参数
    searchInitParam: {}
  });

  /**
   * @description 获取表格数据
   * @return void
   * */
  const getTableList = async (type?: "up") => {
    console.log("查询2");

    state.loading = true;
    try {
      if (type === "up") {
        state.pageable.pageNum++;
        // 已经是最后一页不在加载
        if (state.loadStatus === "noMore") {
          setTimeout(() => {
            state.loading = false;
          }, 500);
          return;
        }
      } else {
        state.pageable.pageNum = 1;
      }
      // 先把初始化参数和分页参数放到总参数里面
      Object.assign(state.totalParam, isPageable ? state.pageable : {}, initParam);

      let params = { ...state.totalParam };
      console.log("查询3", api);

      let data = await api(params);
      console.log("查询3====返回", data);
      Object.assign(state, {
        loadStatus: "more",
        loading: false
      });

      const t_data = (isPageable ? data?.records : data) ?? [];
      if (type === "up") {
        state.tableData.push(...t_data);
      } else {
        state.tableData = t_data;
      }

      // 解构后台返回的分页数据 (如果有分页更新分页信息)
      if (isPageable) {
        const { total, size, current, pages } = data;
        state.loadStatus = pages === current ? "noMore" : "more";
        let pageable = state.pageable;
        if (size && total && current) {
          pageable = {
            pageNum: current,
            pageSize: size,
            total
          };
        }

        updatePageable(pageable);
      }
    } catch (error) {
      console.log(error);
      // uni.hideLoading();
      state.tableData = [];
    }
  };

  /**
   * @description 更新分页信息
   * @param {Object} pageable 后台返回的分页数据
   * @return void
   * */
  const updatePageable = (pageable: Table.Pageable) => {
    Object.assign(state.pageable, pageable);
  };
  return {
    getTableList,
    ...toRefs(state)
  };
};
